#include<stdio.h>
#include<stdlib.h>
#include <ucontext.h>
#include"threadStructure.h"
#include"thread.h"
#include"util.h"

extern thread* MAIN_THREAD;
extern boolean MAIN_IS_THREAD;

int setThreadPriority(thread_t tid, int value){
  //si le main n'est pas un thread, il le devient sinon
  if(MAIN_IS_THREAD == FALSE && mainBecomesThread()==-1)
    return -1;
  thread* th = retrouverLeThread(tid);
  if(!th)
    return -1;
  th->priority.priorite_max = value;
  th->priority.priorite_actu = value;
  return 0;
}

int setMainPriority(int value){
  //si le main n'est pas un thread, il le devient sinon
  if(MAIN_IS_THREAD == FALSE && mainBecomesThread()==-1)
    return -1;
  MAIN_THREAD->priority.priorite_max = value;
  MAIN_THREAD->priority.priorite_actu = value;
  return 0;
}

int setPriority(int value){
  //si le main n'est pas un thread, il le devient sinon
  if(MAIN_IS_THREAD == FALSE && mainBecomesThread()==-1)
    return -1;
  thread* th = getRunningThread();
  if(!th)
    return -1;
  th->priority.priorite_max = value;
  th->priority.priorite_actu = value;
  return 0;
}

int getThreadPriority(thread_t tid){
  //si le main n'est pas un thread, il le devient sinon
  if(MAIN_IS_THREAD == FALSE && mainBecomesThread()==-1)
    return -1;
  return retrouverLeThread(tid)->priority.priorite_actu;
}

int getMainPriority(){
  //si le main n'est pas un thread, il le devient sinon
  if(MAIN_IS_THREAD == FALSE && mainBecomesThread()==-1)
    return -1;
  return MAIN_THREAD->priority.priorite_actu;
}

int getPriority(){
  //si le main n'est pas un thread, il le devient sinon
  if(MAIN_IS_THREAD == FALSE && mainBecomesThread()==-1)
    return -1;
  return getRunningThread()->priority.priorite_actu;
}

void updatePriority(thread* th){
  if (th->priority.priorite_actu) 
    th->priority.priorite_actu --;
  else
    th->priority.priorite_actu = th->priority.priorite_max;
}
